package com.iot.gateway.controller;


import com.iot.gateway.config.MqttGateway;
import com.iot.gateway.model.BinaryProtocol;
import com.iot.gateway.payload.constant.Status;
import com.iot.gateway.service.BinaryMsgHandler;
import com.iot.gateway.service.MsgAbstractHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;


/**
 * @desc 设备topic操作接口
 * @author miki
 */
@RestController
@RequestMapping("/device/topic")
public class DeviceTopicController {

    @Resource
    private MqttGateway mqttGateway;

    @PostMapping("/publish")
    public Mono<Object> sendEvent(@RequestBody Object msg){
        MsgAbstractHandler binaryMsgHandler = new BinaryMsgHandler(new BinaryProtocol());
        return Mono.justOrEmpty(msg).doOnNext(binaryMsgHandler::handle).switchIfEmpty(Mono.just(Status.ERROR));
    }


    /**
     * @desc 直接向tb发送topic
     * @param msg
     * @return
     */
    @PostMapping("/publish-tb")
    public Mono<Object> sendEvent2Tb(@RequestBody Object msg, @RequestHeader("token") String token){

        if(ObjectUtils.isEmpty(token)){
            return Mono.just(Status.ERROR);
        }
        mqttGateway.sendToMqtt(msg.toString(), token);
        return Mono.just(Status.SUCCESS);
    }
}
